package com.qf.proxy.util.http.ge.httpclient;


import cn.hutool.core.util.StrUtil;
import com.qf.proxy.util.SmallTool;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class HttpClientUtil {

    /**
     * 转化各个httpclient返回的html
     */
    public static String parsingHtml(CloseableHttpResponse responce) throws Exception {
        String html = "";
        HttpEntity entity = responce.getEntity();
        if (entity != null) {
            html = EntityUtils.toString(entity, "UTF-8");
            html = html.replace("&nbsp;", " ");
        }
        return html;
    }


    public static Map<String, Object> postWithCode(HttpClientConfigZhang config) {
        Map<String, Object> res = new LinkedHashMap<>();
        String html = "";
        CloseableHttpClient httpClient = HttpClients.custom().setDefaultCookieStore(config.getCookieStore()).setDefaultCredentialsProvider(config.getCredsProvider()).build();
        HttpPost httppost = null;
        long time1 = System.currentTimeMillis();
        CloseableHttpResponse responce;
        try {
            httppost = new HttpPost(config.getUrl());
            if (config.getNvpsList().size() > 0) {
                httppost.setEntity(new UrlEncodedFormEntity(config.getNvpsList(), "utf8"));
            }
            if (StrUtil.isNotEmpty(config.getPostDate())) {
                httppost.setEntity(new StringEntity(config.getPostDate(), "utf-8"));
            }
            httppost.setConfig(config.getRequestConfig());
            if (StrUtil.isNotEmpty(config.getConnection())) {
                httppost.addHeader(HttpHeaders.CONNECTION, config.getConnection());
            }

            if (StrUtil.isNotEmpty(config.getAccept())) {
                httppost.addHeader(HttpHeaders.ACCEPT, config.getAccept());
            }


            if (StrUtil.isNotEmpty(config.getCookie())) {
                httppost.addHeader("Cookie", config.getCookie());
            }


            if (config.getHeaderMap() != null) {
                for (Map.Entry<String, String> entry : config.getHeaderMap().entrySet()) {
                    httppost.addHeader(entry.getKey(), entry.getValue());
                }
            }

            responce = httpClient.execute(httppost);
            int resStatu = responce.getStatusLine().getStatusCode();
            System.out.println("httpclient耗时" + (System.currentTimeMillis() - time1) + "状态码" + resStatu);
            res.put("code", resStatu);

            //if (resStatu == HttpStatus.SC_OK) {
            html = HttpClientUtil.parsingHtml(responce);
            res.put("html", html);

            //}
        } catch (Exception e) {
            e.printStackTrace();
            if (e.toString().contains("java.net.UnknownHostException")) {

            }
            if (e.toString().contains("connect time out")) {
            }
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return res;
    }

    /**
     * 根据各个资源的路径生成对应的pdf
     */
    public static void createFile(String filePath, String fileName, byte[] content)
            throws IOException {
        File folder = new File(filePath);
        if (!folder.exists() && !folder.isDirectory()) {
            SmallTool.printMess("文件夹路径不存在，创建路径:" + filePath);
            folder.mkdirs();
        }
        FileOutputStream fos = new FileOutputStream(filePath + "/" + fileName);
        fos.write(content);
        fos.close();
    }


    /**
     * 配置httprequest的方法
     */
    public static RequestConfig buildRequestConfigure(Boolean redirectFlag, int timeout) {
        if (timeout == 0) {
            timeout = HttpClientConfig.TIME_OUT;
        }
        RequestConfig requestConfig = RequestConfig.custom()
                .setSocketTimeout(timeout).setConnectTimeout(timeout).setRedirectsEnabled(redirectFlag)
                .build();
        return requestConfig;
    }

    /**
     * 通过代理信息生成相应的检索配置信息
     */
    public static HttpClientConfig getSearConfig(String url, String refer, String host, boolean redireFlag) {
        HttpClientConfig config = new HttpClientConfig();
        config.setUrl(url);
        config.setHost(host);
        config.setRefer(refer);
        Map<String, String> headerMap = new HashMap<String, String>();
        if (!StringUtils.isEmpty(host)) {
            headerMap.put(HttpHeaders.HOST, host);
        }
        if (!StringUtils.isEmpty(refer)) {
            headerMap.put(HttpHeaders.REFERER, refer);
        }

        config.setHeaderMap(headerMap);
        RequestConfig requestConfig = HttpClientUtil.buildRequestConfigure(redireFlag, 0);
        config.setRequestConfig(requestConfig);

        return config;
    }

    public static HttpClientConfig getSearConfig(String url) {
        HttpClientConfig config = new HttpClientConfig();
        config.setUrl(url);
        config.setHost("");
        config.setRefer("");
        Map<String, String> headerMap = new HashMap<String, String>();
        if (!StringUtils.isEmpty("")) {
            headerMap.put(HttpHeaders.HOST, "");
        }
        if (!StringUtils.isEmpty("")) {
            headerMap.put(HttpHeaders.REFERER, "");
        }

        config.setHeaderMap(headerMap);
        RequestConfig requestConfig = HttpClientUtil.buildRequestConfigure(true, 0);
        config.setRequestConfig(requestConfig);

        return config;
    }

    /**
     * 通过代理信息生成相应的检索配置信息
     */
    public static HttpClientConfig getSearConfig(String url, String refer, String host, boolean redireFlag, int timeOut) {
        HttpClientConfig config = new HttpClientConfig();
        config.setUrl(url);
        config.setHost(host);
        config.setRefer(refer);
        Map<String, String> headerMap = new HashMap<String, String>();
        if (!StringUtils.isEmpty(host)) {
            headerMap.put(HttpHeaders.HOST, host);
        }
        if (!StringUtils.isEmpty(refer)) {
            headerMap.put(HttpHeaders.REFERER, refer);
        }

        config.setHeaderMap(headerMap);
        RequestConfig requestConfig = HttpClientUtil.buildRequestConfigure(redireFlag, timeOut);
        config.setRequestConfig(requestConfig);

        return config;
    }


    /**
     * 打印cookie查看问题的方法
     */
    public static void printCookie(BasicCookieStore bcs) {
        List<Cookie> list = bcs.getCookies();
        for (Cookie c : list) {
            SmallTool.printMess("cookie信息:" + c.toString());
        }
    }

}
